<?php

namespace app\api\model;

use app\admin\model\usermanage\Users;
use app\api\model\shop\Order;
use app\common\model\TeamPv;
use think\Db;
use think\Exception;
use think\Model;

/**
 * 会员组日志模型
 */
class PvLog extends Model
{

    // 表名
    protected $name = 'pv_log';
    // 开启自动写入时间戳字段
    protected $autoWriteTimestamp = 'int';
    // 定义时间戳字段名
    protected $createTime = 'createtime';
    protected $updateTime = '';
    // 追加属性
    protected $append = [
    ];


    public function give($realname,$account,$pv,$order_id,$user_id)
    {
        if (!$order_id){
            throw new Exception('参数异常');
        }
        if (!$realname){
            throw new Exception('请输入姓名');
        }
        if (!$account){
            throw new Exception('请输入编号');
        }
        if (!$pv){
            throw new Exception('请输入pv值');
        }
        
        $order = Order::get($order_id);
        if ($order->paystate==0){
            throw new Exception('订单未支付');
        }
        
        if ($order->is_pv==1){
            throw new Exception('订单产品pv值已赠送');
        }
        
        $order_pv_send_sum = PvLog::where([
            'user_id'=>$user_id,
            'order_id'=>$order_id,
            'type'=>2,
            'pv_type'=>2,
        ])->sum('pv');

        $order = Order::get($order_id);


        if (round($order->pv-$order_pv_send_sum,1)<round($pv,1)){
            throw new Exception('赠送的pv值大于可赠送的pv值');
        }

        $receive_user = Users::get(['realname'=>$realname,'account'=>$account]);

        if (!$receive_user){
            throw new Exception('接收人不存在');
        }

        $child = $this->getChildList($user_id);

        array_push($child,$user_id);

        if (!in_array($receive_user->id,$child)){
            throw new Exception('接收人不是你的下级');
        }

        $pond = PvLog::where(['user_id'=>$user_id,'order_id'=>$order_id,'pv'=>$pv])->lock(true)->find();
        if ($pond) {
            throw new Exception('已赠送');
        }
        Db::startTrans();

        try {
            $pv_log = new PvLog();

            $pv_log->user_id = $user_id;
            $pv_log->receive_user_id = $receive_user->id;
            $pv_log->setAttr('type',2);
            $pv_log->pv_type = 2;
            $pv_log->order_id = $order_id;
            $pv_log->pv = $pv;
            $pv_log->save();

            $receive_user->pv += $pv;
            $receive_user->fix_pv += $pv;

            if ($receive_user->group_id){
                $Areceive_first_group_pv = GroupPv::where(['first_group_id'=>$receive_user->group_id])->select();

                if (count($Areceive_first_group_pv)>0){
                    foreach ($Areceive_first_group_pv as $k=>$v){
                        $first_group_pv = GroupPv::get($v['id']);
                        $first_group_pv->first_pv += $pv;

                        $first_group_pv->save();
                    }
                }
                $new_pv = GroupPv::get(['new_group_id'=>$receive_user->group_id]);
                if ($new_pv){
                    $new_pv->new_pv += $pv;
                    $new_pv->save();
                }

            }

            if ($receive_user->save()) {

                TeamPv::newTeamPerformance($receive_user->id,0);

                $order_pv_send_sum_2 = PvLog::where([
                    'user_id'=>$user_id,
                    'order_id'=>$order_id,
                    'type'=>2,
                    'pv_type'=>2,
                ])->sum('pv');

                if (bcsub($order->pv,$order_pv_send_sum_2,2)==0){
                    $order->is_pv = 1;
                    $order->issue_pv_time = time();
                    $order->save();
                }

                //$user = User::get($user_id);
                if ($receive_user->contact_id){
                    $parent_arr = $this->getIds($receive_user->contact_id,[]);

                    foreach ($parent_arr as $item){
                        $superior = Users::get($item);
                        $pv_log = new PvLog();

                        $pv_log->user_id = $item;
                        $pv_log->receive_user_id = 0;
                        $pv_log->setAttr('type',3);
                        $pv_log->pv_type = 1;
                        $pv_log->order_id = $order_id;
                        $pv_log->pv = $pv;
                        $pv_log->save();
                        $superior->team_pv += $pv;
                        $superior->save();

                        if ($superior->group_id){
                            $first_group_pv_list = GroupPv::where(['first_group_id'=>$superior->group_id])->select();

                            if (count($first_group_pv_list)>0){
                                foreach ($first_group_pv_list as $k=>$v){
                                    $group_pv_model = GroupPv::get($v['id']);
                                    $group_pv_model->first_pv += $pv;
                                    $group_pv_model->save();
                                }
                            }
                            $new_pv_model = GroupPv::get(['new_group_id'=>$superior->group_id]);
                            if ($new_pv_model){
                                $new_pv_model->new_pv += $pv;
                                $new_pv_model->save();
                            }


                        }
                 
                        //查询团队业绩  发放奖励
                        TeamPv::newTeamPerformance($item,0);
                    }
                }

                Db::commit();
                return true;
            } else {
                Db::rollback();
                throw new Exception('赠送失败');
            }
        } catch (\Exception $e) {
            Db::rollback();
            throw new Exception($e->getMessage());
        }
        
    }

    public function getChildList($user_id)
    {
        //第一次调用时初始化
        static $arr=array();
        //通过邀请码查询当前邀请码下级用户
        $data = Users::where(['contact_id'=>$user_id])
            //->field('id,account,contact_id,realname')
            ->column('id');

        //遍历获取信息，调用当前方法直至没有下级用户
        foreach ($data as $key => $value) {
            $arr[] = $value;
            $this->getChildList($value);
        }
        return $arr;
    }

    public function getIds($id,$arr){
        $parent = Users::get($id);
        array_push($arr,$parent->id);
        if ($parent->contact_id==0){
            return $arr;
        } else {
            return $this->getIds($parent->contact_id,$arr);
        }
    }
}
